package com.ama.controller;

import com.ama.pojo.Company;
import com.ama.pojo.Person;
import com.ama.service.CompanyService;
import com.ama.service.PersonService;
import com.ama.utils.SpringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class QueryListController {
    @RequestMapping("/queryList")
    public void queryList(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String type = request.getParameter("type");
        Map<String, String> map = new HashMap<String, String>();
        ServletContext servletContext = request.getServletContext();
        Enumeration<String> paramNames = request.getParameterNames();
        // 通过循环将表单参数放入键值对映射中
        while(paramNames.hasMoreElements()) {
            String key = paramNames.nextElement();
            String value = request.getParameter(key);
            if(!"".equals(value)){
                map.put(key, value);
            }
        }
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<script>");
        if("个人".equals(type)){
            List<Company> companies = SpringUtils.getBean(CompanyService.class).listAllCompaniesByParams(map);
            servletContext.setAttribute("companies", companies);
            out.println("window.open ('"+request.getContextPath()+"/index.jsp?source=listServlet','_top')");
        }
        if("公司".equals(type)){
            List<Person> persons = SpringUtils.getBean(PersonService.class).listAllPersonsByParams(map);
            servletContext.setAttribute("persons", persons);
            out.println("window.open ('"+request.getContextPath()+"/c_index.jsp?source=listServlet','_top')");
        }
        out.println("</script>");
        out.println("</html>");
        out.flush();
        out.close();
    }
}
